package com.xzj.admin.boot.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.xzj.common.datasource.domain.PageReq;
import com.xzj.common.datasource.domain.PageResp;
import com.xzj.common.datasource.utils.XzjPageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xzj.admin.boot.domain.entity.SysDictItem;
import com.xzj.admin.boot.mapper.SysDictItemMapper;
import com.xzj.admin.boot.service.SysDictItemService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典数据表;(sys_dict_item)表服务实现类
 * @author : http://www.chiner.pro
 * @date : 2024-3-5
 */
@Service
public class SysDictItemServiceImpl implements SysDictItemService{
    @Autowired
    private SysDictItemMapper sysDictItemMapper;
    
    /** 
     * 通过ID查询单条数据 
     *
     * @param id 主键
     * @return 实例对象
     */
    public SysDictItem queryById(long id){
        return sysDictItemMapper.queryById(id);
    }
    
    /** 
     * 分页查询
     *
     * @param pageReq 筛选条件
     * @return 查询结果
     */
    public PageResp<SysDictItem> pageQuery(PageReq<SysDictItem> pageReq){
        return XzjPageUtil.queryPage(pageReq, sysDictItem -> sysDictItemMapper.queryAllByLimit(sysDictItem));
    }
    
    /** 
     * 新增数据
     *
     * @param sysDictItem 实例对象
     * @return 实例对象
     */
    public SysDictItem insert(SysDictItem sysDictItem){
        sysDictItemMapper.insert(sysDictItem);
        return sysDictItem;
    }
    
    /** 
     * 更新数据
     *
     * @param sysDictItem 实例对象
     * @return 实例对象
     */
    public SysDictItem update(SysDictItem sysDictItem){
        sysDictItemMapper.update(sysDictItem);
        return sysDictItem;
    }
    
    /** 
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public boolean deleteById(long id){
        int total = sysDictItemMapper.deleteById(id);
        return total > 0;
    }

    @Override
    public Map<String, List<JSONObject>> queryAllDict() {
        Map<String, List<JSONObject>> result = new HashMap<>();
        List<SysDictItem> sysDictItems = sysDictItemMapper.queryAllByLimit(null);
        for(SysDictItem sysDictItem: sysDictItems){
            JSONObject item = new JSONObject();
            item.put("label",sysDictItem.getName());
            item.put("value",sysDictItem.getValue());
            String code = sysDictItem.getTypeCode();
            if(result.containsKey(code)){
                result.get(code).add(item);
            }else{
                List<JSONObject> items = new ArrayList<>();
                items.add(item);
                result.put(code,items);
            }
        }
        return result;
    }
}